#!/bin/bash
#=========================================
# Filename : check_net.sh
# Author   : Colben
# Create   : 2017-12-04 11:04
#=========================================

PROCS=()

function Quit {
    [ -n "$1" ] && echo -e "\033[31;1mERROR: $1 !\033[0m"
    exit 1
}

function StopPing {
    for pid in ${!PROCS[@]}; do
        kill $pid
    done
    Quit
}

function PingAddr {
    local oldState=
    local newState=
    local alterTime=
    while :; do
        ping -w4 -c2 -q $1 > /dev/null 2>&1
        newState=$?
        [ "$oldState" = "$newState" ] || alterTime="$(date +'%H:%M')"
        oldState=$newState
        if [ '0' = "$newState" ]; then
            echo "\033[32;1m connected\033[0m on $alterTime." > $1
            sleep 8
        else
            echo "\033[31;1m lost\033[0m on $alterTime!" > $1
            sleep 4
        fi
    done
}

# start
[ 0 -eq $# ] && Quit "No hosts found"
mkdir -p /tmp/check_net || Quit "create dir failed"
cd /tmp/check_net || Quit "change dir failed"
trap 2 3 15 "StopPing"

for addr in $@; do
    PingAddr $addr &
    PROCS[$!]="$addr"
done

while :; do
    for pid in ${!PROCS[@]}; do
        if [ ! -f /proc/$pid/stat ]; then
            PingAddr ${PROCS[$pid]} &
            PROC[$!]=PROC[$pid]
            unset PROC[$pid]
        fi
    done
    clear
    for f in $(ls); do
        echo -e "$f:$(cat $f)"
    done
    sleep 4
done


